package com.hmdp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.enums.ErrorCodeEnum;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.RedisConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final ShopMapper shopMapper;

    private final StringRedisTemplate redisTemplate;

    public ShopServiceImpl(ShopMapper shopMapper, StringRedisTemplate redisTemplate) {
        this.shopMapper = shopMapper;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Result queryShopById(Long id) {
        String shopInfo = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        if (!StringUtils.isEmpty(shopInfo)) {
            return Result.ok(JSON.parseObject(shopInfo, Shop.class));
        }

        Shop shop = shopMapper.selectById(id);
        if (ObjectUtils.isEmpty(shop)) {
            // 缓存穿透：缓存与DB中均未命中，缓存空值进行避免并设置TTL
            redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.fail(ErrorCodeEnum.SHOP_EMPTY);
        }
        redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSON.toJSONString(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateShop(Shop shop) {
        // 更新商铺信息
        shopMapper.updateById(shop);
        // 更新DB商铺信息删除缓存，等待根据id查询商铺更新缓存
        redisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
    }
}
